<template>
  <div>
    <div v-for="item in doctors" v-bind:key="item.id">
      <van-card
        :price="item.dPrice"
        :desc="item.dIntroduction"
        :title="item.dName"
        :thumb="item.profile_photo_url"
        editable="false"
      >
        <template #tags>
          <van-tag plain type="primary">{{ item.dPost }}</van-tag>
          <van-tag plain type="primary">{{ item.dSection }}</van-tag>
        </template>
        <template #footer>
          <van-button type="primary" size="normal" @click="guaHaoBtnFun(item)"
            >挂号</van-button
          >
        </template>
      </van-card>
    </div>
    <van-dialog
      v-model:show="show"
      :showConfirmButton="false"
      title="标题"
      show-cancel-button
    >
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-cell title="患者姓名" :value="pname" />
          <van-cell title="医生姓名" :value="guahaoDoctorName" />
          <van-cell title="医生工号" :value="guahaoDoctorID" />
          <van-cell title="职称" :value="dPost" />
          <van-field
            v-model="result"
            is-link
            readonly
            name="picker"
            label="选择器"
            placeholder="点击选择城市"
            @click="showPicker = true"
          />
        </van-cell-group>

        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </van-dialog>
    <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
      <van-picker
        :columns="columns"
        :model-value="pickerValue"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
/* eslint-disable */
import { ref, getCurrentInstance, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import { showDialog } from 'vant';
import LocalStorageUtil from "@/utils/localStorageUtil";
export default {
  setup() {
    const router = useRouter(); // 获取路由实例
    const route = useRoute(); // 获取路由实例
    const { proxy } = getCurrentInstance(); // 获取当前实例
    let doctors = ref([]);
    const date = ref("");
    const today = new Date();
    const minDate = new Date(today.setDate(today.getDate())); // 从明天开始
    const maxDate = new Date(today.setDate(minDate.getDate() + 13)); // 未来两周
    let guahaoDoctorName = ref("");
    let guahaoDocto = ref("");
    let guahaoDoctorID = ref("");
    let dPost = ref("");
    let pname = ref("");
    let show = ref(false);
    let findByTimeRes = ref({});
    let orderDate = ref("");
    let orderTime = ref([]);
    let arId = ref("");
    const formatDate = (date) => {
      const year = date.getFullYear();
      // 获取月份，由于getMonth()返回值从0开始，所以需要加1
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}-${month}-${day}`;
    };
    const onConfirmData = (value) => {
      show.value = false;
      date.value = formatDate(value);
    };
    //提交挂号信息
    const onSubmit = (values) => {
      let params = {
        oStart: values.picker,
        pId: LocalStorageUtil.getLocalStorage("id"),
        dId: guahaoDoctorID.value,
        arId: arId.value,
      };
      proxy
        .$get(`/patient/addOrder`, params)
        .then((res) => {
          console.log("/patient/addOrder->", res);
          if (res.status == "200") {
            showDialog({
              title: "提示",
              message: "挂号成功！请提前10分钟报道！",
            }).then(() => {
              show.value=false
            });
          }
        })
        .cath((error) => {
          //异常处理

        });
      console.log("submit", values);
    };
    const result = ref("");
    const pickerValue = ref([]);
    const showPicker = ref(false);
    const columns = ref([]);

    const onConfirm = ({ selectedValues, selectedOptions }) => {
      console.log("selectedValues->", selectedValues);
      console.log("selectedOptions->", selectedOptions);
      result.value = selectedOptions[0]?.text;
      pickerValue.value = selectedValues;
      showPicker.value = false;
    };
    const guaHaoBtnFun = (doctorInfo) => {
      guahaoDoctorName.value = doctorInfo.dName;
      guahaoDoctorID.value = doctorInfo.dId;
      dPost.value = doctorInfo.dPost;
      pname.value = LocalStorageUtil.getLocalStorage("username");
      show.value = true;
      console.log(findByTimeRes.value);

      for (let key in findByTimeRes.value.data) {
        if (findByTimeRes.value.data[key].doctor.dId == doctorInfo.dId) {
          arId.value = findByTimeRes.value.data[key].arId;

          orderDate.value = findByTimeRes.value.data[key].arTime;
        }
      }
      proxy.$get(`order/findOrderTime?arId=${arId.value}`).then((res) => {
        console.log(res.data);
        const date = new Date(orderDate.value);
        const today = new Date();
        const isToday =
          date.getFullYear() === today.getFullYear() &&
          date.getMonth() === today.getMonth() &&
          date.getDate() === today.getDate();
        console.log("isToday", isToday);
        console.log(orderDate.value);
        var array = [];
        columns.value = []; //初始化一下
        if (!isTimeAfterTarget("09:30") || !isToday) {
          columns.value.push({
            text: "08:30-09:30  " + "余号 " + res.data.eTOn,
            value: "08:30-09:30  " + "余号 " + res.data.eTOn,
          });
          array.push("08:30-09:30  " + "余号 " + res.data.eTOn);
        }
        if (!isTimeAfterTarget("10:30") || !isToday) {
          columns.value.push();
          array.push("09:30-10:30  " + "余号 " + res.data.nTOt);
        }
        if (!isTimeAfterTarget("11:30") || !isToday) {
          columns.value.push({
            text: "10:30-11:30  " + "余号 " + res.data.tTOe,
            value: "10:30-11:30  " + "余号 " + res.data.tTOe,
          });
          array.push("10:30-11:30  " + "   余号 " + res.data.tTOe);
        }
        if (!isTimeAfterTarget("15:30") || !isToday) {
          columns.value.push({
            text: "15:30-16:30  " + "余号 " + res.data.fTOs,
            value: "15:30-16:30  " + "余号 " + res.data.fTOs,
          });
          columns.value.push();
          array.push("15:30-16:30  " + "余号 " + res.data.fTOs);
        }
        if (!isTimeAfterTarget("16:30") || !isToday) {
          columns.value.push({
            text: "15:30-16:30  " + "余号 " + res.data.fTOs,
            value: "15:30-16:30  " + "余号 " + res.data.fTOs,
          });
          array.push("15:30-16:30  " + "余号" + res.data.fTOs);
        }
        if (!isTimeAfterTarget("20:30") || !isToday) {
          columns.value.push({
            text: "16:30-20:30  " + "余号 " + res.data.sTOs,
            value: "16:30-20:30  " + "余号 " + res.data.sTOs,
          });
          array.push("16:30-20:30  " + "余号 " + res.data.sTOs);
        }

        orderTime.value = array;
        console.log("orderTime.value", orderTime.value);
      });
    };
    const isTimeAfterTarget = (timeString) => {
      // 判断时间是否超过timeString(入参格式如：09:30)
      const currentTime = new Date();

      // 解析传入的目标时间字符串，获取小时和分钟
      const [targetHour, targetMinute] = timeString.split(":");

      // 设置要比较的时间
      const targetTime = new Date();
      targetTime.setHours(targetHour);
      targetTime.setMinutes(targetMinute);
      targetTime.setSeconds(0);
      console.log(currentTime > targetTime);

      // 比较当前时间是否超过了目标时间
      return currentTime > targetTime;
    };
    proxy
      .$get(
        `/arrange/findByTime?arTime=${route.query.data}&dSection=${route.query.text}`
      )
      .then((res) => {
        findByTimeRes.value = res;
        for (let key in res.data) {
          doctors.value.push(res.data[key].doctor);
        }
      });
    onMounted(() => {});
    return {
      arId,
      result,
      pickerValue,
      onConfirm,
      showPicker,
      columns,
      orderDate,
      isTimeAfterTarget,
      findByTimeRes,
      guahaoDoctorName,
      guahaoDocto,
      guahaoDoctorID,
      dPost,
      pname,
      onSubmit,
      doctors,
      guaHaoBtnFun, // 返回doctors，使得其在模板中可用
      minDate,
      maxDate,
      onConfirmData,
      date,
      show,
      formatDate,
      orderTime,
    };
  },
};
</script>
<style scoped>
</style>
